﻿using DevExpress.Data.XtraReports.Native;
using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.Utils.About;
using DevExpress.Utils.Html.Internal;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Layout.Core;
using DevExpress.XtraPrinting;
using FastExpressionCompiler.LightExpression;
using HandyControl.Controls;
using HandyControl.Data;
using HandyControl.Tools.Extension;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlaceOrder_Client.Helper;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Client.Views;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Shared.Models.QaingPing;
using PlaceOrder_Shared.ModelsToLily;
using Prism;
using Prism.Commands;
using Prism.DryIoc;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using DelegateCommand = Prism.Commands.DelegateCommand;
using Dialog = HandyControl.Controls.Dialog;
using MessageBox = HandyControl.Controls.MessageBox;
using UserTrade = PlaceOrder_Shared.Models.Common.UserTrade;

namespace PlaceOrder_Client.ViewModels
{
    public class OrderListViewModel:Prism.Mvvm.BindableBase
    {
        public static bool UpdateFlag { get; set; }
     
        public static ClientWebSocketHelper websocket;
        private static readonly Lazy<List<UserTradeVolumeConfig>> _volumeConfigs = new Lazy<List<UserTradeVolumeConfig>>(() => OrderListViewModel.VolumeConfigs);
        public static List<UserTradeVolumeConfig> VolumeConfigs = _volumeConfigs.Value; //静态变量，用于保存自己的买量
        public static List<int> AllowedBrokers = new List<int>();//静态变量，用于保存允许使用的中介，保存的是brokerid


   
        public static List<Tsinfo> LazyTsInfoStaticList;
        public static List<string> LazyTsTypeStaticList;


        private QuanYiOrderServerResponseClass GlobalQSR = new QuanYiOrderServerResponseClass();
        private UserTrade QCT = new UserTrade();
        private bool bResponseReceived = false; //是否收到服务端反馈
        private bool bWaitingforResponse = false; 
        private bool blocking = false;  //只能一个个做

        public static List<UserTrade> StaticTradeList = new List<UserTrade>();
        public static List<UserTrade> AllStaticTradeList = new List<UserTrade>();


        public static List<ChatReceiver> ChatReceivers = new List<ChatReceiver>();
        #region 依赖属性
        private string occupiedBrokerName;

        /// <summary>
        /// 占用中介名
        /// </summary>
        public string OccupiedBrokerName
        {
            get { return occupiedBrokerName; }
            set { occupiedBrokerName = value;RaisePropertyChanged(); }
        }


        private TimeSpan _brokerOccupiedCountdownTime;
        private System.Timers.Timer _brokerOccupiedCountdownTimer;
        /// <summary>
        /// 倒计时显示
        /// </summary>
        public string BrokerOccupiedCountdownDisplay
        {
            get => _brokerOccupiedCountdownTime == TimeSpan.Zero ? "无" : _brokerOccupiedCountdownTime.ToString(@"mm\:ss");
        }

        private bool isLessThanTenMinutes;

        public bool IsLessThanTenMinutes
        {
            get { return isLessThanTenMinutes; }
            set { isLessThanTenMinutes = value; RaisePropertyChanged(); }
        }


        private string websocketInfo;

        public string WebSocketInfo
        {
            get { return websocketInfo; }
            set { websocketInfo = value;RaisePropertyChanged(); }
        }


        private bool isLoading=false;

        public bool IsLoading
        {
            get { return isLoading; }
            set { isLoading= value; RaisePropertyChanged(); }
        }

        private string loadingMessage = "加载中";

        public string LoadingMessage
        {
            get { return loadingMessage; }
            set { loadingMessage = value; RaisePropertyChanged(); }
        }
        
        /// <summary>
        /// 数据总量
        /// </summary>
        private int totalDataCount;

        public int TotalDataCount
        {
            get { return totalDataCount; }
            set { totalDataCount = value; RaisePropertyChanged(); }
        }


        private bool isStartDateChecked=true;

        public bool IsStartDateChecked
        {
            get { return isStartDateChecked; }
            set { isStartDateChecked = value;RaisePropertyChanged(); }
        }


        private bool isEndDateChecked=true;

        public bool IsEndDateChecked
        {
            get { return isEndDateChecked; }
            set { isEndDateChecked = value; RaisePropertyChanged(); }
        }
        #endregion

        public DelegateCommand ReviewMultiViewCommand { get; set; }
        
        public DelegateCommand SearchCommand { get; set; }
        public DelegateCommand ResetCommand { get; set; }
        public Prism.Commands.DelegateCommand<UserTrade> CancelCommand { get; set; } //撤单命令
        public Prism.Commands.DelegateCommand<UserTrade> ChangePriceCommand { get; set; } //改价命令
        public Prism.Commands.DelegateCommand<UserTrade> ReviewCommand { get; set; } //审核命令
        public Prism.Commands.DelegateCommand<UserTrade> ChangeDealTypeCommand { get; set; } //改状态命令（Bid---Tkn，Tkn---Bid）和（Ofr---Gvn,Gvn---Ofr)

        
        public Prism.Commands.DelegateCommand<object> TestCommand { get; set; }
        public Prism.Commands.DelegateCommand TestCommand2 { get; set; }

        public Prism.Commands.DelegateCommand OpenOnHoldPositionsViewCommand { get; set; }
        public Prism.Commands.DelegateCommand<UserTrade> ChangeVisibleCommand { get; set; }

        

        public bool IsFirstStart = true;

        private readonly IDailyData _dailyData;
        private static  Prism.Services.Dialogs.IDialogService _dialogService;

        public Thread mainWebSocketServiceThread;

        public static  List<DateOnly> Holidays = new List<DateOnly>();
        public static  List<DateTime> DateTimeHolidays = new List<DateTime>();

        
        public OrderListViewModel(IDailyData dailyData,Prism.Services.Dialogs.IDialogService dialogService)
        {
            _dailyData = dailyData;
            InitStaticSources();
            WhiteTscodeList = UserHelper.GetTscodeWhiteList();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
         
         
            //LazyTsInfoStaticList = _dailyData.GetAllTsInfos();
            //LazyTsTypeStaticList = _dailyData.GetAllTsTypes();
            //Task.Run(() =>
            //{

            //});
            TestCommand2 = new Prism.Commands.DelegateCommand(() =>
            {
                websocket.UnsubscribeVolumeIndex();
            });
            _dialogService = dialogService;
            //StartConnection();
            //StartConnectionAsync();
     
            InitCommand();
            mainWebSocketServiceThread = new Thread(StartConnection);
            mainWebSocketServiceThread.Start();
            this.SearchHandle();
            Init();
            IsFirstStart = false;
            // 延迟执行 StartConnectionAsync 方法
           
            stopwatch.Stop();
            TimeSpan elapsedTime = stopwatch.Elapsed;
            //Task.Run(async () =>
            //{

            //    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            //    {
            //        LoginViewModel.ShowOrderView();
            //    });
            //});
            // 输出计时结果
            AppLog.WriteInfo($"OrderListViewModel构造函数执行时间: {elapsedTime.Milliseconds} 毫秒");

            Thread checkTradeListThread = new Thread(CheckTradeListTimerStart);
            checkTradeListThread.Start();

            Messenger.Default.Register<string>(this, "orderListViewModelWebSocketClosed", HandleLilyWebSocketClosed);

            //StartBrokerOccupiedCountDownTimer(new TimeSpan());
        }
        private async Task ShowOrderViewAsync()
        {
            // 确保在 UI 线程上执行 UI 操作
            await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            {
                LoginViewModel.ShowOrderView();
            });
        }
        private async void HandleLilyWebSocketClosed(string obj)
        {
           

            // 使用异步延迟，避免阻塞
            await Task.Delay(5000);

            if(websocket!=null)
            {
                AppLog.WriteInfo("OrderListViewModel调用HandleLilyWebSocketClosed");
                websocket.SubscribeLilyServerData(2);
            }
          
            //if (!_webSocket.IsAlive)
            //{
            //    _reconnectTimer.Start();
            //}
        }

        private System.Timers.Timer checkTradeListTimer;
        private int _previousTradeCount;
        private void CheckTradeListTimerStart(object? obj)
        {
            // 设置并启动定时器
            checkTradeListTimer = new System.Timers.Timer(10*60000); // 60秒
            checkTradeListTimer.Elapsed += async (sender, e) => await CheckAndUpdateTradesAsync();
            checkTradeListTimer.Start();
        }

        public void StartBrokerOccupiedCountDownTimer(TimeSpan timeSpan)
        {
            
            if (_brokerOccupiedCountdownTimer != null && _brokerOccupiedCountdownTimer.Enabled)
            {
                AppLog.WriteInfo("中介占用定时器正在使用中");
                return;
            }

            // 初始化倒计时
            _brokerOccupiedCountdownTime = timeSpan;

            // 初始化计时器
            _brokerOccupiedCountdownTimer = new System.Timers.Timer();
            _brokerOccupiedCountdownTimer.Interval = 1000; // 每秒触发一次
            _brokerOccupiedCountdownTimer.Elapsed += TimerTick;
            _brokerOccupiedCountdownTimer.AutoReset = true; // 自动重置为 true 以便每秒触发
            _brokerOccupiedCountdownTimer.Start();
        }

        private void StopBrokerOccupiedCountDownTimer()
        {
            if (_brokerOccupiedCountdownTimer != null && _brokerOccupiedCountdownTimer.Enabled)
            {
                _brokerOccupiedCountdownTimer.Stop();
                _brokerOccupiedCountdownTimer.Dispose();
                _brokerOccupiedCountdownTimer = null;
                _brokerOccupiedCountdownTime = TimeSpan.Zero;
                RaisePropertyChanged(nameof(BrokerOccupiedCountdownDisplay));
                IsLessThanTenMinutes = false;
                AppLog.WriteInfo("中介占用定时器停止。强制停止---StopBrokerOccupiedCountDownTimer");
            }
        }
        private void TimerTick(object? sender, EventArgs e)
        {
            if (_brokerOccupiedCountdownTime.TotalSeconds > 0)
            {
                _brokerOccupiedCountdownTime = _brokerOccupiedCountdownTime.Subtract(TimeSpan.FromSeconds(1));
                RaisePropertyChanged(nameof(BrokerOccupiedCountdownDisplay)); // 使用 Prism 的 RaisePropertyChanged
                                                                              // Check if less than 50 minutes (3000 seconds)
                bool lessThanFiftyMinutes = _brokerOccupiedCountdownTime.TotalMinutes < 10;

                // Use Dispatcher to update the UI on the main thread
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    IsLessThanTenMinutes = lessThanFiftyMinutes;
                });
            }
            else
            {
                IsLessThanTenMinutes = false;
                _brokerOccupiedCountdownTimer.Stop(); // 停止计时器
                AppLog.WriteInfo("中介占用定时器停止。自动停止");
            }
        }

        private string _statusCode;
        private async Task CheckAndUpdateTradesAsync()
        {
            try
            {
                var tradesNew = await Task.Run(() => UserHelper.FindAllXunJiaOrdersAsync());
                if(tradesNew==null|| tradesNew.Count==0)
                {
                    return;
                }
                string codeStr =  string.Join("", tradesNew.Select(t => t.Status));
                //if(_previousTradeCount==0)
                //{
                //    _previousTradeCount=tradesNew.Count;
                //    return;
                //}
                if(string.IsNullOrEmpty(_statusCode ))
                {
                    _statusCode = codeStr;
                    return;
                }
                // 如果新数据的数量与上次保存的数量不同，则更新 TradeList
                if (tradesNew.Count != _previousTradeCount||CheckStatusChanged(codeStr))
                {
                    _statusCode = codeStr;
                    // 更新保存的数量
                    _previousTradeCount = tradesNew.Count;
                    AppLog.WriteInfo("数据变化了，刷新询价单");
                    // 使用 Dispatcher 更新 UI
                    await App.Current.Dispatcher.InvokeAsync(() =>
                    {
                        SearchHandle();
                    });
                    
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                AppLog.WriteError($"CheckAndUpdateTradesAsync异常,{ex.StackTrace}--{ex.Message}");
                Console.WriteLine($"更新交易信息时出错: {ex.Message}");
            }
        }

        private bool CheckStatusChanged(string codeStr)
        {
            if(this._statusCode!=codeStr)
            {
                return true;
            }
            return false;
        }

        
        private async void Init()
        {
            foreach (var r in ChatReceivers)
            {
                AllowedBrokers.Add((int)r.Brokerid);
            }
            //await InitializeAsync();
        }

        private async Task InitializeAsync()
        {
            //ChatReceivers = await _dailyData.GetChatReceiversAsync();

        }
        private void InitCommand()
        {
            SearchCommand = new DelegateCommand(SearchHandle);
            ResetCommand = new DelegateCommand(ResetHandle);
            CancelCommand = new Prism.Commands.DelegateCommand<UserTrade>(Cancel);
            ChangePriceCommand = new Prism.Commands.DelegateCommand<UserTrade>(ChangePrice);
            ReviewCommand = new Prism.Commands.DelegateCommand<UserTrade>(Review);
            TestCommand = new Prism.Commands.DelegateCommand<object>(Test);
            //TestCommand2 = new Prism.Commands.DelegateCommand(Test2);
            ChangeVisibleCommand = new Prism.Commands.DelegateCommand<UserTrade>(ChangeVisible);
            OpenOnHoldPositionsViewCommand = new Prism.Commands.DelegateCommand(OpenOnHoldPositionsView);
            ReviewMultiViewCommand = new DelegateCommand(ReviewMulti);
            ChangeDealTypeCommand = new Prism.Commands.DelegateCommand<UserTrade>(ChangeDealType);
        }

        /// <summary>
        /// 改变交易类型，Bid-Tkn 以及 Ofr-Gvn
        /// </summary>
        /// <param name="trade"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ChangeDealType(UserTrade trade1)
        {
            try
            {

                if (trade1 is UserTrade trade) // 使用类型模式匹配
                {
                    switch (trade.DealType.ToString().ToLower())
                    {
                        case "bid":
                            Growl.InfoGlobal("当前是BID,需要改成TKN");
                            break;
                        case "ofr":
                            Growl.InfoGlobal("当前是OFR,需要改成GVN");
                            break;
                        case "tkn":
                            Growl.InfoGlobal("当前是TKN,需要改成BID");
                            break;
                        case "gvn":
                            Growl.InfoGlobal("当前是GVN,需要改成OFR");
                            break;
                        case "卖出":
                            Growl.InfoGlobal("当前是卖出,需要改成GVN");
                            break;
                       
                        case "买入":
                            Growl.InfoGlobal("当前是买入,需要改成TKN");
                            break;
                   
                    }
                }
               
            }
            catch(Exception ex)
            {
                AppLog.WriteError("ChangeDealType改变交易类型异常" +ex.Message+ex.StackTrace);
            }
        }



        /// <summary>
        /// 主从表可见性
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ChangeVisible(UserTrade userTrade)
        {
            // 确保传入的 userTrade 和其 Children 不为空
            if (userTrade != null && userTrade.Children != null && userTrade.Children.Count > 0)
            {
                // 获取所有子项的 TradeNum
                var childTradeNums = userTrade.Children.Select(child => child.TradeNum).ToList();

                // 查找 TradeList 中所有 TradeNum 匹配的 UserTrade 对象
                foreach (var trade in TradeList.Where(t => childTradeNums.Contains(t.TradeNum)))
                {
                    // 切换这些 UserTrade 对象的 IsChildrenVisibility 属性
                    trade.IsChildrenVisibility = !trade.IsChildrenVisibility;
                }
            }
        }

        private void Test2()
        {
           
        }

        private void Test(object obj)
        {
           
        }

        private OnHoldPositionsView _onHoldPositionsView;
        /// <summary>
        /// 打开当前持仓页面（也是单例）
        /// </summary>
        private void OpenOnHoldPositionsView()
        {

            var existedOnHoldPositionsWindow = PrismApplication.Current.Windows.OfType<OnHoldPositionsView>().FirstOrDefault();
            if(existedOnHoldPositionsWindow!=null)
            {
                Growl.InfoGlobal("已开启持仓页面,请检查");
                existedOnHoldPositionsWindow.Activate();
                return;
            }
            // 如果实例已经存在，激活它
            if (_onHoldPositionsView != null)
            {
                Growl.InfoGlobal("已开启持仓页面,请检查");
                _onHoldPositionsView.Activate();
                return;
            }

            // 创建新的 OnHoldPositionsView 实例
            _onHoldPositionsView = new OnHoldPositionsView
            {
                Title = $"{UserHelper.NickName}:当前持仓",
                WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
            };

            // 订阅窗口关闭事件，以便释放实例
            _onHoldPositionsView.Closed += (s, e) => _onHoldPositionsView = null;

            // 使用 Dispatcher 确保在 UI 线程上显示窗口
            PrismApplicationBase.Current.Dispatcher.Invoke(() =>
            {
                _onHoldPositionsView.Show();
            });
         }



        /// <summary>
        /// 执行申诉 复核
        /// </summary>
        private void Review(UserTrade userTrade)
        {
            //测试
             //UserHelper.GetTradeInfoByTime("240210.IB",null,null);
            //var temp41 = UserHelper.FindAllXunJiaOrdersAsync();

            //var temp1 = UserHelper.SearchAllPingCangOrder();
            //var temp2 = UserHelper.SearchAllNoPingCangOrder();
            //var temp3 = UserHelper.SearchAllWeiYue();
            //var temp4 = UserHelper.SelectAllUserTrade();
            //var temp5 = UserHelper.FindAllChatMessagesAsync(2, "f09639756a47415fb4fbf6d31febbad4");
       
            if (blocking)
            {
                Growl.WarningGlobal("有正在执行的任务");
                return;
            }
            
            var viewModel = new RequestReviewViewModel(userTrade);
            var parentWindow = PrismApplication.Current.MainWindow;
            selectedUserTrade = new UserTrade(userTrade);
            // 创建新窗口并设置DataContext
            var window = new RequestReviewView
            {
                DataContext = viewModel,
                Owner = parentWindow, // 设置父窗口
                WindowStartupLocation = WindowStartupLocation.CenterOwner, // 设置窗口启动位置为父窗口中心
                Title = $"申请复议窗口,券码：{userTrade.TsCode},下单时间：{userTrade.Time}"
            };
            // 设置关闭窗口的委托
            viewModel.CloseWindowAction = window.Close;
            window.ShowDialog();

            //window.Close();
        }


        /// <summary>
        /// 执行申诉(多条询价单） 复核
        /// </summary>
        private void ReviewMulti()
        {
            //测试
            //UserHelper.GetTradeInfoByTime("240210.IB",null,null);
            //var temp41 = UserHelper.FindAllXunJiaOrdersAsync();

            //var temp1 = UserHelper.SearchAllPingCangOrder();
            //var temp2 = UserHelper.SearchAllNoPingCangOrder();
            //var temp3 = UserHelper.SearchAllWeiYue();
            //var temp4 = UserHelper.SelectAllUserTrade();
            //var temp5 = UserHelper.FindAllChatMessagesAsync(2, "f09639756a47415fb4fbf6d31febbad4");
            var userTrade = this.TradeList.Where(o => o.IsSelected).ToList();
            if(userTrade==null||userTrade.Count()==0)
            {
                Growl.WarningGlobal("请选中有异议的询价单!");
                return;
            }
            if (userTrade.Count() > 4)
            {
                Growl.WarningGlobal("最多选择4个有争议的询价单~");
                return;
            }
            if (blocking)
            {
                Growl.WarningGlobal("有正在执行的任务");
                return;
            }

            var viewModel = new RequestReviewViewModel(userTrade);
            var parentWindow = PrismApplication.Current.MainWindow;

            int height = 200;
            if(userTrade.Count()>2)
            {
                height = 250;
            }
            // 创建新窗口并设置DataContext
            var window = new RequestReviewView
            {
                DataContext = viewModel,
                Owner = parentWindow, // 设置父窗口
                WindowStartupLocation = WindowStartupLocation.CenterOwner, // 设置窗口启动位置为父窗口中心
                Title = $"申请复议窗口(询价单）",
                Height=height
            };
            // 设置关闭窗口的委托
            viewModel.CloseWindowAction = window.Close;
            window.ShowDialog();

            //window.Close();
        }

        private UserTrade selectedUserTrade = null;
        /// <summary>
        /// 执行改价
        /// </summary>
        private void ChangePrice(UserTrade userTrade)
        {
            if (OrderListViewModel.IsQiangPing)
            {
                Growl.ErrorGlobal("当前强平中，禁止一切操作");
                return;
            }
            if (blocking)
            {
                MessageBox.Show("有正在执行的任务", "Error");
                return;
            }
            selectedUserTrade = new UserTrade(userTrade);
            if (userTrade != null)
            {
                if (userTrade.Status != 0 & userTrade.Status != 1 & userTrade.Status != 4 & userTrade.Status != 7& userTrade.Status != 23)
                {
                    MessageBox.Show("该单状态不对，无法改价", "Error");
                    return;
                }
            }
            var viewModel = new ChangePriceViewModel(userTrade);
            viewModel.ChangePriceRequested -= ChangePrice;
            viewModel.ChangePriceRequested += ChangePrice;
            var parentWindow = PrismApplication.Current.MainWindow;

            // 创建新窗口并设置DataContext
            var window = new ChangePriceView
            {
                DataContext = viewModel,
                Owner = parentWindow, // 设置父窗口
                WindowStartupLocation = WindowStartupLocation.CenterOwner, // 设置窗口启动位置为父窗口中心
                Title = $"改价窗口,券码：{userTrade.TsCode},下单时间：{userTrade.Time}"
            };
            window.ShowDialog();

        }

        private async void ChangePrice(object? sender, ChangePriceArgs e)
        {
            try
            {
                var newTrade = e.Trade;
                if (await SendModify(selectedUserTrade, newTrade))
                {
                    AppLog.WriteInfo("改价成功!"+newTrade.ToString());
                    //MessageBox.Show("改价成功");
                }else
                {
                    AppLog.WriteError("改价失败：");
                }
                
            }
            catch(Exception ex)
            {
                AppLog.WriteError("改价异常：" + ex.StackTrace + ex.Message);
            }
            finally
            {
                this.SearchHandle();
            }
 
        }
        private async Task<bool> SendModify(UserTrade olduserTrade,UserTrade newuserTrade)
        {
            DateOnly dtStart = DateOnly.FromDateTime(DateTime.Now);
            //var tempTsInfo = _dailyData.GetBondByCode(olduserTrade.TsCode);
            //decimal CurrentPrice = _dailyData.GetLatestPrice(tempTsInfo, false);


            var TempTrades = await UserHelper.GetTradeHistoriesAsync(olduserTrade.TsCode, dtStart, DateOnly.FromDateTime(DateTime.Now), 1, true);
            if(TempTrades==null|| TempTrades.Count()==0)
            {
                return false;
            }
            decimal CurrentPrice = TempTrades.LastOrDefault().TradePrice;
            string orderDeliveryInfo = olduserTrade.DealType;
            if(orderDeliveryInfo=="卖出")
            {
                orderDeliveryInfo = "ofr";
            }else
            {
                orderDeliveryInfo = "bid";
            }
            string order = $"{olduserTrade.DealType} {olduserTrade.TsCode.Replace(".IB", "")} 价格 改 {newuserTrade.Price} ,量改{newuserTrade.Volume}";

            if (orderDeliveryInfo == "bid") //买单，所以改-现在必须>0.25
            {
                if (CurrentPrice - newuserTrade.Price > 0.01M)
                {
                    Growl.WarningGlobal("买单不允许价差超过1BP，请检查！" + "当前最新价为" + CurrentPrice);
                    return false;
                }
                if (CurrentPrice-newuserTrade.Price> 0.0025M)
                {
                    var result = MessageBox.Show($"是否确认改价？当前是买单---当前价差超过0.25BP,当前最新价为{CurrentPrice}" + "\r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (result == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
                else
                {
                    var result = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
            }else if (orderDeliveryInfo == "ofr")
            {
                if (newuserTrade.Price - CurrentPrice > 0.01M)
                {
                    Growl.WarningGlobal($"卖单不允许价差超过1BP，请检查！, 当前最新价为{CurrentPrice}");
                    return false;
                }
                if (newuserTrade.Price- CurrentPrice>0.0025M)
                {
                    var result = MessageBox.Show($"是否确认改价？当前是卖单---当前价差超过0.25BP , 当前最新价为{CurrentPrice} \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
                else
                {
                    var result = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.No)
                    {
                        blocking = false;
                        AppLog.WriteInfo("用户取消改价了");
                        return false;
                    }
                }
            }



                //if (Math.Abs(tPrice.Value - CurrentPrice) > 0.006M)
                //{
                //    if (MessageBox.Show("下单价与当前价差超过0.6BP，是否下单？ \r\n", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                //    {
                //        return;
                //    }
                //}
                QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
            CurrentGuid = Guid.NewGuid();
            qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePrice;
            //QCT.Command = order;
            //QCT.Price = newuserTrade.Price;
            qsr.Trade = newuserTrade;
            qsr.Trade.ChatID = UserHelper.UserID.ToString();
            qsr.Guid = CurrentGuid;
            qsr.Token = UserHelper.Token;
            //qsr.Trade.BrokerID = 2; 
            string msg;
            try
            {
                if (bIsConnected)
                {
                    //bResponseReceived = false;
                    //clientWebsocket.SendResponseToServer(qsr);
                    //IsLoading = true;
                    //Task.Run(() =>
                    //{
                    //    WaitingResponseThread();
                    //});

                    bResponseReceived = false;
                    blocking = true;
                    IsLoading = true;
                    LoadingMessage = "正在发送改价指令...";
                    websocket.SendResponseToServer(qsr);
                    await WaitForWebSocketResponse(); // 等待 WebSocket 响应

                    if (GlobalQSR.Code != 0)
                    {
                        MessageBox.Show("风控没通过，请检查价格。" + GlobalQSR.Message);
                        IsLoading = false;
                        blocking = false;
                        return false;
                    }
                    IsLoading = false;
                    blocking = false;
                    LoadingMessage = "发送成功!";
                }
                else
                {
                    Growl.ErrorGlobal("连接失败，请检查");
                    blocking = false;
                    AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
                    return false;
                }
            }
            catch
            {
                MessageBox.Show("无法连接服务器，请联系管理员！", "Error");      
                AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
                return false;
            }
            finally
            {
                blocking = false;
            }

            return false;
            //var result1 = MessageBox.Show("中介是否允许改价？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            //if (result1 == MessageBoxResult.No)
            //{
            //    blocking = false;
            //    QCT.Price = olduserTrade.Price;
            //    AppLog.WriteInfo($"中介拒绝改价,{QCT.Command},{QCT.Target}" + olduserTrade.UserTradeID.ToString());
            //    return false;
            //}
            //else
            //{
            //    CurrentGuid = Guid.NewGuid();
            //    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm;
            //    qsr.Code = 0;
            //    qsr.Trade = newuserTrade;
            //    qsr.Token = UserHelper.Token;
            //    qsr.Guid = CurrentGuid;
            //}


            //try
            //{
            //    if (bIsConnected)
            //    {
            //        bResponseReceived = false;
            //        blocking = true;
            //        IsLoading = true;
            //        LoadingMessage = "正在发送确认改价指令...";
            //        websocket.SendResponseToServer(qsr);
            //        await WaitForWebSocketResponse(); // 等待 WebSocket 响应

            //        IsLoading = false;

            //        LoadingMessage = "发送成功!";
            //        blocking = false;
            //    }
            //    else
            //    {
            //        blocking = false;
            //        MessageBox.Show("无法连接发送服务器，请联系管理员");
            //        AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
            //        return false;
            //    }
            //}
            //catch(Exception ex)
            //{
            //    blocking=false;
            //    Growl.ErrorGlobal("无法连接服务器，请联系管理员！"+ ex.Message);
            //    //MessageBox.Show("无法连接发送服务器，请联系管理员");
            //    AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
            //    return false;
            //}
            //finally
            //{
            //    blocking = false;
            //}
            //return true;
        }

        public static Guid CurrentGuid;
        /// <summary>
        /// 执行撤单
        /// </summary>
        private async void Cancel(UserTrade t)
        {
            if (OrderListViewModel.IsQiangPing)
            {
                Growl.ErrorGlobal("当前强平中，禁止一切操作");
                return;
            }
            if (blocking)
            {
                //MessageBox.Show("有正在执行的任务", "Error");
                return;
            }
            // Use await instead of .Result
            blocking = true;
            var a = await UserHelper.GetTradeByTradeIdApiAsync((int)t.UserTradeID);
            if (t != null)
            {
                if (a == null) { return; }
                else
                {
                    if (a.Status != t.Status)
                    {
                        SearchHandle();
                    }
                }
                if (a.Status == 3 || a.Status == 5)
                {
                    MessageBox.Show("该单状态不对，无法撤单", "Error");
                    return;
                }


                // 在需要显示消息框的地方调用该方法
                var result = HandyControl.Controls.MessageBox.Show(
                    $"是否撤单？ \r\n券号:{t.TsCode}\r\n价格:{t.Price}\r\n询量:{t.Volume}\r\n剩余询量：{t.OnHoldVolume}\r\n交割日:{t.DeliveryDate:yyyy-MM-dd}\r\n下单时间{t.Time}",
                    "撤单确认！",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {  
                    blocking = false;
                    return;
                }

                selectedUserTrade = new UserTrade(t);
                CurrentGuid = Guid.NewGuid();
                UserTrade trade = new UserTrade();
                trade.Command = "ref";
                trade.ChatID = OrderListViewModel.ChatReceivers.Where(o=>o.Brokerid==t.BrokerID).FirstOrDefault().ChatId;
                trade.Target = t.Target;
                QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
                qsr.UserID = UserHelper.UserID;
                qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.Withdraw;
                qsr.Trade = t;
                qsr.Guid = CurrentGuid;
                qsr.Trade.UserID = UserHelper.UserID;
                try
                {

                    if (bIsConnected)
                    {
                        //websocket.SendResponseToServer(qsr);
                        // 显示加载对话框并等待 WebSocket 响应
                        // 显示加载对话框并等待 WebSocket 响应
                        bResponseReceived = false;
                        blocking = true;
                        IsLoading = true;
                        LoadingMessage = "正在发送初次撤单指令...";
                        websocket.SendResponseToServer(qsr);
                        await WaitForWebSocketResponse(); // 等待 WebSocket 响应

                        IsLoading = false;

                        LoadingMessage = "发送成功!";
                    }
                    else
                    {
                        //Growl.ErrorGlobal("服务器未连接,请检查");
                        AppLog.WriteError($"撤单：微信撤单失败,{t.Command},{t.Target}");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("无法连接服务器，请联系管理员！", "Error");
                    AppLog.WriteError($"撤单：微信撤单失败,{t.Command},{t.Target}", t.UserTradeID.ToString());
                    return;
                }
                finally
                {
                   blocking = false;
                }
                //// 在需要显示消息框的地方调用该方法
                //var result2 = HandyControl.Controls.MessageBox.Show(
                //    $"中介是否允许撤单？\r\n券号:{t.TsCode}\r\n价格:{t.Price}\r\n询量:{t.Volume}\r\n交割日:{t.DeliveryDate:yyyy-MM-dd}",
                //    "确认",
                //    MessageBoxButton.YesNo,
                //    MessageBoxImage.Question);

                //if (result2 == MessageBoxResult.No)
                //{
                //    blocking = false;
                //    AppLog.WriteError($"撤单：中介拒绝撤单,{t.Command},{t.Target}", t.UserTradeID.ToString());
                //    return;
                //}
                //try
                //{
                //    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.Withdrawed;
                //    bResponseReceived = false;
                //    blocking = true;
                //    IsLoading = true;
                //    LoadingMessage = "正在发送中介确认撤单指令...";
                //    websocket.SendResponseToServer(qsr);
                //    await WaitForWebSocketResponse(); // 等待 WebSocket 响应

                //    IsLoading = false;

                //    LoadingMessage = "发送成功!";

                //}
                //catch
                //{
                //    MessageBox.Show("撤单失败", "异常");
                //}
                //finally
                //{
                //    blocking=false;
                //}
                //MessageBox.Show("撤单完成", "信息");
                //t.Status = 5;
                //AppLog.WriteError($"撤单：成功,{t.Command},{t.Target}" + t.UserTradeID.ToString());
                //OrderListViewModel.UpdateFlag = true;
            }
        }
        private async Task WaitForWebSocketResponse()
        {
            DateTime dtStart = DateTime.Now;
            TimeSpan ts = new TimeSpan();
            ts = DateTime.Now - dtStart;

            while (ts.TotalSeconds < ClientWebSocketHelper.GlobalTimeOut)
            {
                if (bResponseReceived)
                {
                    if (GlobalQSR.Code == 0)
                    {
                      
                        QCT.Id = GlobalQSR.Trade.Id;
                        QCT.Time = GlobalQSR.Trade.Time;
                        bWaitingforResponse = false;
                        string info = $"券码：{GlobalQSR.Trade.TsCode}" +
                            $"指令：{GlobalQSR.Trade.Command}," +
                            $"中介：{GlobalQSR.Trade.Broker}" +
                            $"类型：{GlobalQSR.Trade.DealType}," +
                            $"交割日期：{GlobalQSR.Trade.DeliveryDate}" +
                            $"询量：{GlobalQSR.Trade.Volume}" +
                            $"价格：{GlobalQSR.Trade.Price}" +
                            $"指令：{GlobalQSR.Trade.OrderType}" +
                            $"状态：{GlobalQSR.Trade.StatusText}" +
                            $"操作人：{GlobalQSR.Trade.UserName}"+"\r\n\n"
                            +"服务端返回状态————"+GlobalQSR.Message;
                        if (GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm|| GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.ChangePrice)
                        {
                            //Growl.SuccessGlobal("改价成功!"+"\r\n"+ GlobalQSR.Message);
                            //Growl.SuccessGlobal($"已成功发送 撤单 到 {GlobalQSR.Trade.Target}");

                            AppLog.WriteInfo("已成功发送 改价 到!" + info);
                        }
                        else if (GlobalQSR.DataType == QuanYiServerBaseClass.DataTypeEnum.Withdraw)
                        {
                            AppLog.WriteInfo("已成功发送 撤单 到!" + info);
                            Growl.SuccessGlobal($"已成功发送 撤单 到 {GlobalQSR.Trade.Target}");
                        }

                     
                        //if (GlobalQSR.Message == null)
                        //{
                        //    MessageBox.Show("成功创建" + info, "信息");
                        //    AppLog.WriteInfo("成功创建" + info);
                        //}
                        //else
                        //{
                        //    MessageBox.Show("成功!"+"\r\n" + GlobalQSR.Message + info, "信息");
                        //    AppLog.WriteInfo("成功!" + GlobalQSR.Message + info);
                        //}

                    }
                    else
                    {
                        //Growl.SuccessGlobal("执行失败!" + "\r\n" + GlobalQSR.Message);
                        bWaitingforResponse = false;
                        MessageBox.Show(GlobalQSR.Message, "执行失败!");
                        return;
                    }
                    bResponseReceived = false;
                    return;
                }

                await Task.Delay(10);
                ts = DateTime.Now - dtStart;
            }

            bWaitingforResponse = false;
            MessageBox.Show("连接服务器超时", "信息");
        }

        private void ResetHandle()
        {
            this.SelectedStartDate = DateTime.Now.Date;
            this.SelectedEndDate = DateTime.Now.Date;
            this.IsEndDateChecked = true;
            this.IsStartDateChecked = true;
            this.SearchText = string.Empty;
            this.SearchHandle();
        }



        private bool isSearching = false; // 是否在查询中

        private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1);

        /// <summary>
        /// 查询方法（关键词查找）
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        private async void SearchHandle()
        {
            //var s = this.TradeList;
            await _semaphoreSlim.WaitAsync();
            try
            {
                //if (isSearching)
                //{
                //    return; // 防止同时多次调用
                //}
                //isSearching = true;
                if (IsStartDateChecked && IsEndDateChecked && SelectedEndDate < SelectedStartDate)
                {
                    Growl.InfoGlobal("请检查日期，截止日不能小于开始日");
                    return;
                }
                await SearchAllAsync();

                if (!string.IsNullOrEmpty(SearchText) || IsStartDateChecked || IsEndDateChecked)
                {
                    var results = TradeList.Where(item => SearchSelected(item, SearchText)).ToList();

                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        // 禁用事件处理程序，避免递归调用
                        TradeList.CollectionChanged -= TradeList_CollectionChanged;

                        // 清空当前集合，并添加新元素
                        TradeList.Clear();
                        foreach (var result in results)
                        {
                            TradeList.Add(result);
                        }

                        // 重新启用事件处理程序
                        TradeList.CollectionChanged += TradeList_CollectionChanged;

                        // 更新 UI 绑定的属性
                        StaticTradeList = TradeList.ToList(); // 更新 StaticTradeList
                        TotalDataCount = TradeList.Count;

                        isSelected = true;
                    });

                    if (results.Count == 0 && !IsFirstStart)
                    {
                        var messageBoxInfo = new MessageBoxInfo
                        {
                            Message = "找不到符合条件的记录",
                            Caption = "提示",
                            IconBrushKey = ResourceToken.InfoBrush,
                            IconKey = ResourceToken.InfoGeometry,
                            Button = MessageBoxButton.OK
                        };

                        //HandyControl.Controls.MessageBox.Show(messageBoxInfo);
                    }
                }
                else
                {
                    isSelected = false;
                    TotalDataCount = TradeList.Count;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("SearchHandle异常" + ex.StackTrace + ex.Message);
            }
            finally
            {
                this.blocking = false;
                _semaphoreSlim.Release();
                //isSearching = false; // 操作完成，允许下一次调用
            }
        }


        //private async void SearchHandle()
        //{
        //    if (IsStartDateChecked && IsEndDateChecked)
        //    {
        //        if (SelectedEndDate < SelectedStartDate)
        //        {
        //            Growl.InfoGlobal("请检查日期，截止日不能小于开始日");
        //            return;
        //        }
        //    }

        //    await SearchAllAsync();

        //    if (!string.IsNullOrEmpty(SearchText)||IsStartDateChecked==true||IsEndDateChecked==true)
        //    {
        //        // 创建一个临时列表来保存搜索结果
        //        var results = new List<UserTrade>();

        //        // 遍历所有交易，搜索符合条件的项目
        //        foreach (var item in TradeList)
        //        {
        //            if (SearchSelected(item, SearchText))
        //            {
        //                results.Add(item);
        //            }
        //        }
        //        PrismApplication.Current.Dispatcher.Invoke(() =>
        //        {
        //            // 清空当前的TradeList
        //            TradeList.Clear();
        //        });

        //        //if (results.Count > 0)
        //        //{
        //        //    // 逐个添加搜索结果到TradeList
        //        //    foreach (var result in results)
        //        //    {
        //        //        TradeList.Add(result);
        //        //    }
        //        //    isSelected = true;
        //        //    TotalDataCount = TradeList.Count;
        //        //}
        //        if (results.Count > 0)
        //        {
        //            // 使用一个临时集合来存储结果
        //            var tempTradeList = new List<UserTrade>(TradeList);
        //            tempTradeList.AddRange(results);

        //            // 确保在UI线程中进行集合的修改
        //            PrismApplication.Current.Dispatcher.Invoke(() =>
        //            {
        //                // 禁用事件处理程序，避免递归调用
        //                TradeList.CollectionChanged -= TradeList_CollectionChanged;

        //                // 清空当前集合，并添加新元素
        //                TradeList.Clear();
        //                foreach (var item in tempTradeList)
        //                {
        //                    TradeList.Add(item);
        //                }

        //                // 重新启用事件处理程序
        //                TradeList.CollectionChanged += TradeList_CollectionChanged;

        //                // 更新 UI 绑定的属性
        //                StaticTradeList = tempTradeList;
        //                TotalDataCount = TradeList.Count;

        //                isSelected = true;
        //            });
        //        }

        //        else
        //        {
        //            // 没有找到符合条件的记录，显示提示框
        //            if(!IsFirstStart)
        //            {
        //                var messageBoxInfo = new MessageBoxInfo
        //                {
        //                    Message = "找不到符合条件的记录",
        //                    Caption = "提示",
        //                    IconBrushKey = ResourceToken.InfoBrush,
        //                    IconKey = ResourceToken.InfoGeometry,
        //                    Button = MessageBoxButton.OK

        //                };

        //                //HandyControl.Controls.MessageBox.Show(messageBoxInfo);
        //            }


        //            // 重新加载所有数据
        //            //SearchAll();
        //            isSelected = false;
        //            TotalDataCount = TradeList.Count;
        //        }
        //    }
        //    else
        //    {
        //        // 如果没有输入搜索文本，加载所有数据
        //        //SearchAll();
        //        isSelected = false;
        //        TotalDataCount = TradeList.Count;
        //    }
        //}


        private bool SearchSelected(UserTrade item, string searchText)
        {
            // 检查搜索文本是否匹配
            bool textMatch = false;
            if (string.IsNullOrEmpty(searchText))
            {
                textMatch = true;
            }else
            {
                 textMatch= IsContains(item.TsCode, searchText) || IsContains(item.Target, searchText) ||
                             IsContains(item.Broker, searchText) || IsContains(item.DealType, searchText) ||
                             IsContains(item.StatusText, searchText) || IsContains(item.Price.ToString(), searchText)||
                             IsContains(item.Volume.ToString(), searchText)||
                             IsContains(item.TradeNum.ToString(), searchText);
            }
            

            // 检查时间是否匹配
            bool timeMatch = true;
            // 检查日期的有效性
          

            // 如果启用开始日期过滤
            if (IsStartDateChecked && SelectedStartDate != null)
            {
                timeMatch = item.Time.Date >= SelectedStartDate;
            }

            // 如果启用截止日期过滤
            if (IsEndDateChecked && SelectedEndDate != null)
            {
                timeMatch &= item.Time.Date <= SelectedEndDate;
            }

            // 同时满足文本匹配和时间匹配
            return textMatch && timeMatch;
            //之后要加上时间的过滤
        }
        
        private bool IsContains(string str1, string str2)
        {
            if (string.IsNullOrEmpty(str1)) return false;
            if (str1.Contains(str2)) return true;
            else return false;
        }
        //private void Init()
        //{
        //    SearchAll();
        //}

        /// <summary>
        /// 默认搜索全部交易记录（自己的）
        /// </summary>
        //private  void SearchAll()
        //{
        //    TradeList = new ObservableCollection<UserTrade>();
        //    TradeList = _dailyData.GetUserTrades(UserHelper.UserID).ToObservableCollection();
        //    if (TradeList.Count != 0)
        //        TotalDataCount = TradeList.Count;

        //}
        private async Task SearchAllAsync()
        {
            TradeList = new ObservableCollection<UserTrade>();

            var tradesNew = await Task.Run(() => UserHelper.FindAllXunJiaOrdersAsync());
            if(tradesNew==null||tradesNew.Count==0)
            {
                return;
            }
            this._previousTradeCount = tradesNew.Count;
            var tradeModels = new List<UserTrade>();
            // 处理父项和子项的递归函数
            void AddTradeWithChildren(UserTrade trade)
            {
                // 将当前的 trade 添加到列表中
                tradeModels.Add(trade);

                // 如果有子项，递归处理每个子项
                if (trade.Children != null)
                {
                    foreach (var child in trade.Children)
                    {
                        var childTrade = new UserTrade
                        {
                            Status = (int)child.Status,
                            Price = child.Price,
                            RealPrice = child.RealPrice,
                            Volume = child.Volume,
                            RealVolume = child.RealVolume,
                            OnHoldVolume = child.OnHoldVolume,
                            TsCode = child.TsCode,
                            Time = (DateTime)child.Time,
                            TradeTime = child.TradeTime,
                            TradeTime2 = child.TradeTime2,
                            UpdateTime = child.UpdateTime,
                            IsChildren = true,
                            DealType = child.DealType,
                            UserTradeID = child.UserTradeID,
                            ChannelID = child.ChannelID,
                            DeliveryDate = child.DeliveryDate,
                            DeliverySpeed = child.DeliverySpeed,
                            Target = child.Target,
                            IsCancelable = child.Status != 3 && child.Status != 5,
                            IsChangepriceable = child.Status != 3 && child.Status != 5,
                            QiangPingId = !string.IsNullOrEmpty(child.QiangPingId) ? "1" : null,
                            TradeNum = child.TradeNum,
                            IsVisibility = false
                        };

                        // 递归调用，以处理子项的子项（如果有的话）
                        AddTradeWithChildren(childTrade);
                    }
                }
            }

            // tradeModels = tradesNew.Select(trade => new UserTrade
            //{
            //    // 根据需要设置 UserTrade 对象的属性
            //    // 例如：
            //    BrokerID = trade.BrokerId,
            //    Status = trade.Status,
            //    Price = (decimal)trade.Price,
            //    RealPrice = trade.RealPrice,
            //    Volume = (int.Parse)(trade.Volume),
            //    RealVolume = trade.RealVolume,
            //    OnHoldVolume = (int.Parse)(trade.RestVolume),

            //    TsCode = trade.Tscode,
            //    Time = trade.CreateTime,
            //    TradeTime = trade.TradeTime,
            //    TradeTime2 = trade.TradeTime2,
            //    UpdateTime = trade.UpdateTime,
            //    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
            //    UserTradeID = trade.UserTradeId,
            //    ChannelID = trade.ChannelId,
            //    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
            //    DeliverySpeed = trade.DeliverySpeed,
            //    Target = trade.Target,
            //    IsCancelable = trade.Status == 3 || trade.Status == 5 ? false : true,
            //    IsChangepriceable = trade.Status == 3 || trade.Status == 5 ? false : true,
            //    QiangPingId = !string.IsNullOrEmpty(trade.QiangpingId) ? "1" : null,
            //    TradeNum = trade.TradeNum,
            //    IsVisibility = trade.Children != null && trade.Children.Any(),
            //    IsChildren = false,
            //    Children = trade.Children?.Select(child => new UserTrade
            //    {
            //        Status = (int)child.Status,
            //        Price = child.Price ?? 0m,
            //        RealPrice = child.Price,
            //        Volume = int.Parse(child.Volume),
            //        RealVolume = child.RealVolume,
            //        OnHoldVolume = (int.Parse)(child.RestVolume),
            //        TsCode = child.Tscode,
            //        Time = (DateTime)child.CreateTime,
            //        TradeTime = child.TradeTime,
            //        TradeTime2 = child.TradeTime2,
            //        UpdateTime = child.UpdateTime,
            //        IsChildren=true,
            //        DealType = child.Direction == "bond_0" ? "买入" : (child.Direction == "bond_1" ? "卖出" : "未知"),
            //        UserTradeID = child.UserTradeId,
            //        ChannelID = child.ChannelId,
            //        DeliveryDate = DateOnly.FromDateTime(child.DeliveryTime),
            //        DeliverySpeed = child.DeliverySpeed,
            //        Target = child.Target,
            //        IsCancelable = child.Status != 3 && child.Status != 5,
            //        IsChangepriceable = child.Status != 3 && child.Status != 5,
            //        QiangPingId = !string.IsNullOrEmpty(child.QiangpingId) ? "1" : null,
            //        TradeNum = child.TradeNum,
            //        IsVisibility = true
            //    }).ToObservableCollection()
            //    // 其他属性赋值
            //}).ToList();
            // 处理每个父项，并添加到 tradeModels 列表中
            foreach (var trade in tradesNew)
            {
                var parentTrade = new UserTrade
                {
                    BrokerID = trade.BrokerId,
                    Status = trade.Status,
                    Price = (decimal)trade.Price,
                    RealPrice = trade.RealPrice,
                    Volume = int.Parse(trade.Volume),
                    RealVolume = trade.RealVolume,
                    OnHoldVolume = int.Parse(trade.RestVolume),

                    TsCode = trade.Tscode,
                    Time = trade.CreateTime,
                    TradeTime = trade.TradeTime,
                    TradeTime2 = trade.TradeTime2,
                    UpdateTime = trade.UpdateTime,
                    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"),
                    UserTradeID = trade.UserTradeId,
                    ChannelID = trade.ChannelId,
                    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                    DeliverySpeed = trade.DeliverySpeed,
                    Target = trade.Target,
                    IsCancelable = trade.Status == 3 || trade.Status == 5 ? false : true,
                    IsChangepriceable = trade.Status == 3 || trade.Status == 5 ? false : true,
                    QiangPingId = !string.IsNullOrEmpty(trade.QiangpingId) ? "1" : null,
                    TradeNum = trade.TradeNum,
                    IsVisibility = trade.Children != null && trade.Children.Any(),
                    IsChildren = false,
                    Children = trade.Children?.Select(child => new UserTrade
                    {
                        Status = (int)child.Status,
                        Price = child.Price ?? 0m,
                        RealPrice = child.Price,
                        Volume = int.Parse(child.Volume),
                        RealVolume = child.RealVolume,
                        OnHoldVolume = (int.Parse)(child.RestVolume),
                        TsCode = child.Tscode,
                        Time = (DateTime)child.CreateTime,
                        TradeTime = child.TradeTime,
                        TradeTime2 = child.TradeTime2,
                        UpdateTime = child.UpdateTime,
                        IsChildren = true,
                        DealType = child.Direction == "bond_0" ? "买入" : (child.Direction == "bond_1" ? "卖出" : "未知"),
                        UserTradeID = child.UserTradeId,
                        ChannelID = child.ChannelId,
                        DeliveryDate = DateOnly.FromDateTime(child.DeliveryTime),
                        DeliverySpeed = child.DeliverySpeed,
                        Target = child.Target,
                        IsCancelable = child.Status != 3 && child.Status != 5,
                        IsChangepriceable = child.Status != 3 && child.Status != 5,
                        QiangPingId = !string.IsNullOrEmpty(child.QiangpingId) ? "1" : null,
                        TradeNum = child.TradeNum,
                        IsVisibility = false
                    }).ToObservableCollection()
                    // 其他属性赋值
                };
            
                // 处理父项及其子项
                AddTradeWithChildren(parentTrade);
            }

            this._statusCode = string.Join("", tradesNew.Select(t => t.Status));
            TradeList = tradeModels.ToObservableCollection();
            AllStaticTradeList = tradeModels;
            if (TradeList.Count != 0)
            {
                TotalDataCount = tradesNew.Count;
                this._previousTradeCount = tradesNew.Count;
            }
        }

        private async Task InitStaticSources()
        {
            VolumeConfigs = await Task.Run(() => _dailyData.GetUserTradeVolumeConfig(UserHelper.UserID));//0831
            OrderListViewModel.ChatReceivers = await UserHelper.GetChatReceiversAsync();
            Holidays =await PlaceOrder_Core.Services.Instances.DailyData.GetHolidaysAsync();
            // 获取今天的日期
            //DateTime today = DateTime.Today;
            //DateTime oneMonthLater = today.AddMonths(1);

            //// 计算未来一个月内的所有双休日（周六、日）
            //List<DateOnly> weekendsInNextMonth = Enumerable
            //    .Range(0, (oneMonthLater - today).Days) // 生成从今天到一个月内的日期范围
            //    .Select(offset => DateOnly.FromDateTime(today.AddDays(offset))) // 将 DateTime 转为 DateOnly
            //    .Where(date => date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) // 过滤出周六和周日
            //    .ToList();

            //// 合并假期列表和双休日列表，并去重
            //Holidays = Holidays
            //    .Concat(weekendsInNextMonth) // 合并两个列表
            //    .Distinct() // 去重
            //    .OrderBy(date => date) // 按日期排序
            //    .ToList();

            // 将 DateOnly 转换为 DateTime
            List<DateTime> dateTimeHolidays = Holidays.Select(dateOnly => dateOnly.ToDateTime(new TimeOnly(0, 0))).ToList();
            // 赋值给 DateTimeHolidays
            DateTimeHolidays = dateTimeHolidays;
            await ShowOrderViewAsync();
        }

        private bool bIsConnected = false;

        public static string ServerIP = UserHelper.GetLXWServerIP();

        public bool IsConnectLily = false;
        public void StartConnection()
        {
            string msg;
            websocket = new ClientWebSocketHelper(_dailyData);
            //websocket.SubscribeLilyTradeData();
            //ServerIP = _dailyData.GetConfigs("WeChatServer")[0].Value;


            //websocket.ServerDisconnectedEvent -= Websocket_OrderServerDisconnectedEvent;//客户端与服务端断连时触发
            websocket.ServerConnectedEvent -= Websocket_ServerConnectedEvent;//客户端连接服务端时触发
            websocket.QuanYiOrderClientMessageEvent -= WebSocketHelper_QuanYiOrderClientMessageEvent;
            websocket.SubscribeLilyTradeEvent -= Websocket_SubscribeLilyTradeEvent;//成功撤单时触发
            websocket.LilyInformEvent -= Websocket_LilyInformEvent; ;//收到lily的消息（强平、聊天）直接时触发


            //websocket.QiangpingInformEvent += Websocket_LilyInformEvent;//收到强平预警时触发

            websocket.ServerDisconnectedEvent += Websocket_OrderServerDisconnectedEvent;//客户端与服务端断连时触发
            websocket.ServerConnectedEvent += Websocket_ServerConnectedEvent;//客户端连接服务端时触发
            websocket.QuanYiOrderClientMessageEvent += WebSocketHelper_QuanYiOrderClientMessageEvent;
            websocket.SubscribeLilyTradeEvent += Websocket_SubscribeLilyTradeEvent;//成功撤单时触发
            websocket.LilyInformEvent += Websocket_LilyInformEvent; ;//收到lily的消息（强平、聊天）直接时触发


            websocket.SubscribeLilyServerData(2);
            websocket.LilyDisconnectEvent -= Websocket_LilyDisconnectEvent;

            websocket.LilyDisconnectEvent += Websocket_LilyDisconnectEvent;
            Messenger.Default.Register<QuanYiOrderServerResponseClass>(this, MessageToken.SendToOrderListViewOrderInfo, true, WebSocketHelper_QuanYiOrderClientMessageEvent);

            Messenger.Default.Register<string>(this, MessageToken.SendReviewMessage, SendReviewMessageToServer);


            Messenger.Default.Register<QuanYiOrderServerResponseClass>(this, MessageToken.SendChatMessage, SendChatMessageToServer);
            Messenger.Default.Register<QuanYiOrderServerResponseClass>(this, MessageToken.ShakeWindow, SendWindowShakeToServer);

            if (websocket.ClientStartConnectToServer(ServerIP, 38888, true))
            {
                bIsConnected = true;
                //return true;
            }
            else
            {
                // 启动定时器尝试重连
                StartReconnectTimer();
                bIsConnected = false;
                //return false;
            }
        }
        public async Task<bool> StartConnectionAsync()
        {
            string msg;
            websocket = new ClientWebSocketHelper(_dailyData);
            //ServerIP = _dailyData.GetConfigs("WeChatServer")[0].Value; 0831

            websocket.ServerDisconnectedEvent -= Websocket_OrderServerDisconnectedEvent; //客户端与服务端断连时触发
            websocket.ServerConnectedEvent -= Websocket_ServerConnectedEvent; //客户端连接服务端时触发
            websocket.QuanYiOrderClientMessageEvent -= WebSocketHelper_QuanYiOrderClientMessageEvent;
            websocket.SubscribeLilyTradeEvent -= Websocket_SubscribeLilyTradeEvent; //成功撤单时触发
            websocket.LilyInformEvent -= Websocket_LilyInformEvent; //收到lily的消息（强平、聊天）直接时触发
            websocket.LilyDisconnectEvent -= Websocket_LilyDisconnectEvent;
           


            websocket.ServerDisconnectedEvent += Websocket_OrderServerDisconnectedEvent; //客户端与服务端断连时触发
            websocket.ServerConnectedEvent += Websocket_ServerConnectedEvent; //客户端连接服务端时触发
            websocket.QuanYiOrderClientMessageEvent += WebSocketHelper_QuanYiOrderClientMessageEvent;
            websocket.SubscribeLilyTradeEvent += Websocket_SubscribeLilyTradeEvent; //成功撤单时触发
            websocket.LilyInformEvent += Websocket_LilyInformEvent; //收到lily的消息（强平、聊天）直接时触发
            websocket.SubscribeLilyServerData(2);
            websocket.LilyDisconnectEvent += Websocket_LilyDisconnectEvent;

            Messenger.Default.Register<QuanYiOrderServerResponseClass>(this, MessageToken.SendToOrderListViewOrderInfo, true, WebSocketHelper_QuanYiOrderClientMessageEvent);
            Messenger.Default.Register<string>(this, MessageToken.SendReviewMessage, SendReviewMessageToServer);
            Messenger.Default.Register<QuanYiOrderServerResponseClass>(this, MessageToken.SendChatMessage, SendChatMessageToServer);

            bool isConnected = await websocket.ClientStartConnectToServerAsync(ServerIP, 38888, true);
            if (isConnected)
            {
                bIsConnected = true;
                return true;
            }
            else
            {
                StartReconnectTimer();
                bIsConnected = false;
                return false;
            }
        }

        private void Websocket_OrderServerDisconnectedEvent(string guid)
        {
            AppLog.WriteError($"OrderListViewModel 与 Lily服务端断开连接，正在尝试重连");
            //Growl.WarningGlobal("与服务端断开连接，正在尝试重连");
            try
            {
                StartReconnectTimer();
            }
            catch (Exception ex)
            {
                AppLog.WriteError("Websocket_OrderServerDisconnectedEvent异常" + ex.Message + ex.StackTrace);
            }
        }

        private void Websocket_LilyDisconnectEvent()
        {
            // 如果正在尝试重连，则直接返回
           try
            {
                AppLog.WriteError("orderlistview断连了--Websocket_LilyDisconnectEvent" );
                if (isLilyReconnecting)
                    return;

                // 设置正在重连标志
                isLilyReconnecting = true;
                // 如果定时器已存在，则进行清理
                if (reconnectLilyTimer != null)
                {
                    // 停止定时器
                    reconnectLilyTimer.Stop();

                    // 解除事件处理程序
                    reconnectLilyTimer.Elapsed -= ReconnectLilyTimer_Elapsed;

                    // 释放资源
                    reconnectLilyTimer.Dispose();

                    // 设为 null
                    reconnectLilyTimer = null;
                }
                // 创建并配置定时器
                reconnectLilyTimer = new System.Timers.Timer();
                reconnectLilyTimer.Interval = 5000; // 设置重连间隔为5秒
                reconnectLilyTimer.Elapsed -= ReconnectLilyTimer_Elapsed;

                reconnectLilyTimer.Elapsed += ReconnectLilyTimer_Elapsed;
                reconnectLilyTimer.AutoReset = true; // 设置为true，确保定时器重复执行

                // 启动定时器
                reconnectLilyTimer.Start();
            }
            catch(Exception ex)
            {
                AppLog.WriteError(ex.Message + "orderlistview断连--Websocket_LilyDisconnectEvent" + ex.StackTrace);
            }
        }

        private void ReconnectLilyTimer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            try
            {
                
                if (websocket != null)
                {
                    AppLog.WriteInfo("ReconnectLilyTimer_Elapsed");
                    websocket.SubscribeLilyServerData(2);
                }
                if(websocket.IsOrderListViewModelWebSocketConnected)
                {
                    this.reconnectLilyTimer.Stop();
                    isLilyReconnecting = false;
                }

            }
            catch(Exception ex)
            {
                AppLog.WriteError("lily服务端关闭-ReconnectLilyTimer_Elapsed" + ex.Message + ex.StackTrace);
            }
        }


        /// <summary>
        /// websocket接收缓存（去重）
        /// </summary>
        private static HashSet<string> processedLilyMessages = new HashSet<string>();


        private int Status = 0;

        public static List<LilyOccupyBrokerInfo> occupyBrokerInfos;
        public static int userStatus;
        /// <summary>
        /// lily 数据（客户端接收推送）
        /// </summary>
        /// <param name="qiangPingOrder"></param>
        private void Websocket_LilyInformEvent(string Message)
        {
            try
            {
                // 解析 JSON 数据
                JObject jsonMessage = JObject.Parse(Message);

                // 提取信息
                string dataKey = jsonMessage["dataKey"]?.ToString();
                string dataType = jsonMessage["dataType"]?.ToString();
                //AppLog.WriteInfo("lily -orderlistviewmodel 所有消息" + Message);

                switch (dataType)
                {
                    case "pong":
                        AppLog.WriteFatal("收到心跳包" + dataKey + dataType);
                        return;
                         
                    #region 丢弃不做处理的
                    case "tradeamountlimit":
                    case "qiangping": //刘老师发来的撤单/改价，服务端处理即可
                        return;
                        break;
                    #endregion


                    case "brokeroccupyinfo":
                        var occupyInfo = jsonMessage["data"].ToString();
                        // 将 JSON 反序列化为 List<LilyOccupyBrokerInfo>
                        occupyBrokerInfos = JsonConvert.DeserializeObject<List<LilyOccupyBrokerInfo>>(occupyInfo);
                        CheckOccupiedBrokerAndManageTimer(occupyBrokerInfos);
                        Messenger.Default.Send(occupyBrokerInfos, MessageToken.OccupyBrokerInfo);


                        break;

                    case "userStatusInfo":
                        var data1 = jsonMessage["data"];
                        AppLog.WriteInfo($"lilywebsocket---{UserHelper.NickName}的userStatusInfo状态是{data1.ToString()}");
                         userStatus = int.Parse(data1?["status"].ToString());
                       
                      
                        if (userStatus == 0)
                        {
                            this.OrderStatus = "正常";
                            IsQiangPing = false;
                        }
                        if (userStatus == 2||userStatus==3)
                        {
                            this.OrderStatus = "账户锁定，禁止下单！";
                            IsQiangPing = true;
                        }

                        if (userStatus == 3)
                        {
                            MessageBox.Show("账号异常,强退！");
                            PrismApplication.Current.Shutdown();
                        }
                        if (userStatus ==1)
                        {
                            //this.OrderStatus = "异常封控中。";
                            this.OrderStatus = "警告";
                            
                        }
                        if (userStatus == 5)
                        {
                            this.OrderStatus = "被劫持中";
                            //IsQiangPing = true;

                        }
                        Messenger.Default.Send(userStatus, MessageToken.FengKong);
                        break;
                    case "qiangping_inform":
                        {
                            AppLog.WriteFatal("强平通知qiangping_inform" + "--" + jsonMessage);
                            string actionType = jsonMessage["actionType"]?.ToString();
                            var data = jsonMessage["data"];

                            string pingcangType = data?["pingcangType"]?.ToString();
                            string pingcangAction = data?["pingcangAction"]?.ToString();
                            string message = data?["message"]?.ToString();
                            string messageId = data?["messageId"]?.ToString();
                            int userId = data?["userId"]?.ToObject<int>() ?? 0;
                            int restSeconds = 0;
                            var restSecondsToken = data?["restSeconds"];
                            if (restSecondsToken != null)
                            {
                                int.TryParse(restSecondsToken.ToString(), out restSeconds);
                            }
                            //restSeconds = 110;
                            string sendTime = data?["sendTime"]?.ToString();
                            this.WebSocketInfo += "lily强平数据" + message+"\r\n";
                            switch (pingcangType)
                            {
                                case "kuisun":

                                        if (pingcangAction == "cancel")
                                        {
                                            Growl.SuccessGlobal(message);
                                            PrismApplication.Current.Dispatcher.Invoke(() =>
                                            {
                                                foreach (System.Windows.Window window in PrismApplication.Current.Windows)
                                                {
                                                    AppLog.WriteInfo("Tag:" + window.Tag?.ToString());
                                                    if (window.Tag?.ToString() == "QiangPingCountDownView")
                                                    {
                                                        window.Close();
                                                        Growl.InfoGlobal(message);
                                                        break;
                                                    }
                                                }
                                            });
                                            return;
                                        }else if (pingcangAction == "execute")
                                        {
                                            Growl.ErrorGlobal(message);

                                            PrismApplication.Current.Dispatcher.Invoke(() =>
                                        {
                                            foreach (System.Windows.Window window in PrismApplication.Current.Windows)
                                            {
                                                AppLog.WriteInfo("Tag:" + window.Tag?.ToString());
                                                if (window.Tag?.ToString() == "QiangPingCountDownView")
                                                {
                                                    window.Close();
                                                    Growl.InfoGlobal(message);
                                                    break;
                                                }
                                            }
                                        });

                                        return;
                                        }else if(pingcangAction=="warn")
                                        {
                                            Growl.WarningGlobal(message);
                                            //Growl.ErrorGlobal($"当日亏损已超出允许范围，已开启强平预警，{restSeconds}秒后将锁定交易权限。");
                                            PrismApplication.Current.Dispatcher.Invoke(() =>
                                            {
                                                OrderListViewModel.ShowQiangPing(message, restSeconds);
                                            });
                                            return;
                                        }
                                       
                                    


                                    break;
                                //case "kuisun":
                                //    //this.OrderStatus = "亏损强平！";
                                //    message = "亏损强平 —— " + message;


                                //    PrismApplication.Current.Dispatcher.Invoke(() =>
                                //    {
                                //        OrderListViewModel.ShowQiangPing(message, restSeconds);
                                //    });
                                //    break;
                                case "execute":
                                    //this.OrderStatus = "执行强平！";
                                    //IsQiangPing = true;
                                 
                                    Growl.WarningGlobal(message);
                                    PrismApplication.Current.Dispatcher.Invoke(() =>
                                    {
                                        OrderListViewModel.ShowQiangPing(message, restSeconds);
                                    });
                                    
                                    break;
                                case "cancel":
                                    //this.OrderStatus = "取消强平！";
                                    message = "取消强平 —— 倒计时取消" + message;
                                    Growl.SuccessGlobal(message);
                                    PrismApplication.Current.Dispatcher.Invoke(() =>
                                    {
                                        foreach (System.Windows.Window window in PrismApplication.Current.Windows)
                                        {
                                            if (window.Name == "QiangPingCountDownView")
                                            {
                                                window.Close();
                                                Growl.InfoGlobal(message);
                                                break;
                                            }
                                        }
                                    });
                                    //IsQiangPing = false;
                                    //PrismApplication.Current.Dispatcher.Invoke(() =>
                                    //{
                                    //    OrderListViewModel.ShowQiangPing(message, restSeconds);
                                    //});
                                    break;
                            }

                            UserHelper.ConsumeQiangPingMessageAsync(messageId);
                        }
                        break;


                    case "chat_message":
                        // 创建一个唯一标识符（例如组合时间戳和消息内容）
                        // 格式化 createTime 为 "yyyy-MM-dd HH:mm:ss"
                        RootFromLily root = jsonMessage.ToObject<RootFromLily>();
                        ChatDataFromLily item = root.Data;
                        string formattedCreateTime = new DateTime(item.CreateTime.Year, item.CreateTime.MonthValue, item.CreateTime.DayOfMonth, item.CreateTime.Hour, item.CreateTime.Minute, item.CreateTime.Second)
                                                     .ToString("yyyy-MM-dd HH:mm:ss");
                        List<ChatMessage> newMessages = new List<ChatMessage>();


                        this.WebSocketInfo += "聊天消息" + item.ChatMessage+"\r\n";
                        int direction = item.Direction;
                        int brokerId = item.BrokerId;
                        string chatMsg = item.ChatMessage;
                        int chatId = item.ChatId;
                        string tradeId = item.TradeId;
                        //string brokerName = item.BrokerName;
                        // 将字符串转换为 DateTime 类型
                        DateTime createTime;
                        if (DateTime.TryParse(formattedCreateTime, out createTime))
                        {
                            // 转换成功
                           // Console.WriteLine(createTime);
                        }
                        else
                        {
                            // 转换失败，处理错误
                            AppLog.WriteError("转换错误");
                            Console.WriteLine("Invalid date format");
                        }

                        // 创建一个唯一标识符（例如组合时间戳和消息内容）
                        string uniqueIdentifier = $"{formattedCreateTime}_{item.ChatMessage}";

                        // 检查是否已经处理过该消息
                        if (!processedMessages.Contains(uniqueIdentifier))
                        {
                            // 获取中介名称
                            string brokerName = ChatReceivers.Where(o => o.Brokerid == item.BrokerId).FirstOrDefault()?.Company;

                            // 生成消息信息
                            string chatInfo = $"消息内容：{item.ChatMessage}\r\n" +
                                              $"时间：{formattedCreateTime}\r\n" +
                                              $"中介：{brokerName}";
                            Growl.InfoGlobal($"收到一条新消息：{chatInfo}");

                            // 添加到已处理集合中
                            processedMessages.Add(uniqueIdentifier);
                            long parsedTradeId = 0;
                            if (!string.IsNullOrEmpty(tradeId) && !long.TryParse(tradeId, out parsedTradeId))
                            {
                                parsedTradeId = 0;
                            }
                            var chatMsgModel = new ChatMessage() {Id= item.Id, Direction = (short?)direction, ChatMessageInfo = chatMsg, CreateTime = createTime,BrokerId=brokerId,BrokerName=brokerName??"未知",ChatId= chatId,TradeId= parsedTradeId };
                            newMessages.Add(chatMsgModel);
                        }
                        //string brokerName = ChatReceivers.Where(o=>o.Brokerid==item.BrokerId).FirstOrDefault().Company;
                        //string chatinfo = $"消息内容：{item.ChatMessageInfo}\r\n" +
                        //    $"时间：{item.CreateTime}\r\n" +
                        //    $"中介：{brokerName}";
                        //item.BrokerName = brokerName;
                        //Growl.InfoGlobal($"收到一条新消息：{chatinfo}");


                        // 仅对新的消息列表进行发送
                        if (newMessages.Count > 0)
                        {
                            //Messenger.Default.Send(newMessages, MessageToken.NewChatMessageIn);
                            // Sending the message to trigger the registered handler
                            Messenger.Default.Send("", "CheckIfChatWindowOpened"); //检查聊天窗口是否打开，未开则开


                            Messenger.Default.Send(newMessages, MessageToken.SendChatMessage);
                            // 发送消息
                            Messenger.Default.Send("YourMessageContent", "ActivateChatMessageWindow");

                            //if (newMessages[0].Direction==1)
                            //{
                            //    SearchHandle();
                            //}
                        }
                        break;

                    case "accept_bond_1":
                    case "accept_bond_0":
                    case "deal_bond_0":
                    case "deal_bond_1":
                    case "request_cancel_bond_0":
                    case "request_cancel_bond_1":
                    case "confirm_cancel_bond_0":
                    case "confirm_cancel_bond_1":
                    case "deny_cancel_bond_0":
                    case "deny_cancel_bond_1":
                    case "xiugaichangedeny_bond_0":
                    case "xiugaichangedeny_bond_1":
                    case "usertradechange_bond_0":
                    case "usertradechange_bond_1":
                    case "xiugaichangeconfirm_bond_0":
                    case "xiugaichangeconfirm_bond_1":

                        // 反序列化JSON
                        // 提取所需字段
                        // 构造消息标识符
                        string messageKey = $"{dataKey}-{dataType}";
                        // 检查消息是否已经处理
                        if (processedLilyMessages.Contains(messageKey))
                        {
                            // 如果已经处理过，跳过操作
                            AppLog.WriteError("已有一条相同消息" + dataKey);
                            return;
                        }
                        // 检查消息是否已经处理
                        // 缓存新的消息
                        processedLilyMessages.Add(messageKey);
                        if (jsonMessage["data"] == null)
                        {
                            // 如果已经处理过，跳过操作
                            AppLog.WriteError("jsonMessage[\"data\"]为空" + dataKey);
                            return;
                        }
                        // 检查是否存在 tscode 字段
                        if (jsonMessage["data"]["tscode"] == null)
                        {
                            // 如果 jsonMessage["data"] 中没有 tscode 字段，记录错误并跳过操作
                            AppLog.WriteError("jsonMessage[\"data\"] 中没有 tscode 字段: " + dataKey);
                            SearchHandle();
                            return;
                        }
                        string tscode = jsonMessage["data"]["tscode"].ToString();
                        string volume = jsonMessage["data"]["volume"].ToString();
                        double price = jsonMessage["data"]["price"].ToObject<double>();
                        string createTime1 = jsonMessage["data"]["createTime"].ToString();
                        string deliveryTime = jsonMessage["data"]["deliveryTime"].ToString();
                        string remark = jsonMessage["data"]["remark"].ToString();
                        int status = jsonMessage["data"]["status"].ToObject<int>();
                       
                       
                        //string msg = $"券码：{tscode}，量：{volume}" + "\r\n"
                        //    + $"价格：{price}，创建日期：{createTime1}，交割日期：{deliveryTime}" + "\r\n";
                        string info = LilyMessageConverterHelper.ConvertToRealMessage(dataType);
                        //MessageBox.Show($"{info}"+"\r\n" + msg);
                   

                        AppLog.WriteInfo($"收到{dataType}消息" + Message);
                        //this.WebSocketInfo = "收到accept_bond_1消息" + Message;

                        this.WebSocketInfo += "lily消息" + dataType+Message + "\r\n";
                        Growl.InfoGlobal($"系统收到消息 —— {info}");

                        SearchHandle();
                        Messenger.Default.Send("null", MessageToken.RefreshCang);
                        break;

                    case "xunjiachangerequest_bond_1":
                    case "xunjiachangerequest_bond_0":
                        string info1 = LilyMessageConverterHelper.ConvertToRealMessage(dataType);
                        Growl.InfoGlobal($"系统收到改价消息 —— {info1}");
                        SearchHandle();
                        break;
                    default:
                        AppLog.WriteInfo("lily -orderlistviewmodel 其余消息" + Message);
                        //this.WebSocketInfo = "lily -orderlistviewmodel 其余消息" + Message;
                        SearchHandle();
                        break;
                }
     
                //OrderListViewModel.ShowQiangPing(qiangPingMessage);
            
            }
            catch (Exception ex)
            {
                AppLog.WriteError("收到强平异常Websocket_InformEvent" + ex.Message + ex.StackTrace);
            }
        }

        private void CheckOccupiedBrokerAndManageTimer(List<LilyOccupyBrokerInfo>? occupyBrokerInfos)
        {
            // 检查是否存在 Occupy = true 且 Occupyier 为当前用户ID的记录
            if (ChatReceivers == null || ChatReceivers.Count == 0)
            {
                AppLog.WriteError("聊天中介未加载完，空");
                return;
            }
            var isOccupiedByCurrentUser = occupyBrokerInfos.Any(info => info.Occupy && info.Occupyier == UserHelper.UserID);
           
            if (isOccupiedByCurrentUser)
            {
                // 检查是否存在 Occupy = true 且 Occupyier 为当前用户ID的记录
                var occupiedInfo = occupyBrokerInfos.FirstOrDefault(info => info.Occupy && info.Occupyier == UserHelper.UserID);
                if(occupiedInfo==null)
                {
                    return;
                }
                //加锁
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    OccupiedBrokerName = ChatReceivers.Where(o => o.Brokerid == occupiedInfo.BrokerId && o.ChannelId == occupiedInfo.ChannelId).FirstOrDefault().FormattedTarget;
                });
                
                StartBrokerOccupiedCountDownTimer(new TimeSpan(0,59,59)); // 开启定时器
            }
            else
            {
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    OccupiedBrokerName = string.Empty;
                });
                //解锁
                StopBrokerOccupiedCountDownTimer(); // 关闭定时器
            }
        }

        private void Websocket_QiangpingEvent(QiangPingInform qiangPingOrder)
        {

            try
            {

            }
            catch (Exception ex)
            {
                AppLog.WriteError("listviewmodel强平" + ex.Message + qiangPingOrder.ToString());
            }
        }

       
    

      

        private System.Timers.Timer reconnectTimer;
        private System.Timers.Timer reconnectLilyTimer;
        private void StartReconnectTimer()
        {
            // 如果正在尝试重连，则直接返回
            if (isReconnecting)
                return;

            // 设置正在重连标志
            isReconnecting = true;

            // 创建并配置定时器
            reconnectTimer = new System.Timers.Timer();
            reconnectTimer.Interval = 3000; // 设置重连间隔为15秒
            reconnectTimer.Elapsed += ReconnectTimer_Elapsed;
            reconnectTimer.AutoReset = true; // 设置为true，确保定时器重复执行

            // 启动定时器
            reconnectTimer.Start();
        }
        private int reconnectAttempt = 0; // 记录重连尝试次数
        private void ReconnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 在定时器触发时执行重连操作
            bool isConnected = websocket.ClientStartConnectToServer(ServerIP, 38888, true);

            if (isConnected)
            {
                // 连接成功，停止定时器并重置标志
                reconnectTimer.Stop();
                isReconnecting = false;
                bIsConnected = true;
                reconnectAttempt = 0; // 重置重连尝试次数
                // 可以在这里执行连接成功后的逻辑
            }
            else
            {
                AppLog.WriteWarn("连接LXW服务器失败");
                //Growl.WarningGlobal($"连接服务器失败,第{++reconnectAttempt}次");
                // 连接失败，可以记录日志或者显示提示信息等
            }
        }
        private bool isReconnecting = false;
        private bool isLilyReconnecting = false;
        private bool TryReconnect()
        {
            // 尝试重新连接的逻辑
            //string ServerIP = _dailyData.GetConfigs("WeChatServer")[0].Value;
            bool isConnected = websocket.ClientStartConnectToServer(ServerIP, 38888, true);

            if (isConnected)
            {
                // 重新连接成功
                bIsConnected = true;
                return true;
            }
            else
            {
                // 重新连接失败
                bIsConnected = false;
                return false;
            }
        }

        private readonly object _sendLockObject = new object();
        /// <summary>
        /// 发送快捷消息至服务端
        /// </summary>
        /// <param name="class"></param>
        private void SendChatMessageToServer(QuanYiOrderServerResponseClass qsr)
        {
            lock (_sendLockObject)
            {
                try
                {
                    if (websocket.SendResponseToServer(qsr))
                    {
                        Growl.SuccessGlobal($"发送消息成功至服务端,内容{qsr.Message}");
                    }
                    else
                    {
                        Growl.WarningGlobal($"发送消息至服务端失败,内容{qsr.Message}");
                    }
                }
                catch (Exception ex)
                {
                    Growl.WarningGlobal($"发送消息至服务端异常,内容{qsr.Message}+{ex.Message}");
                }
            }

        }


        /// <summary>
        /// 发送窗口抖动至服务端
        /// </summary>
        /// <param name="class"></param>
        private void SendWindowShakeToServer(QuanYiOrderServerResponseClass qsr)
        {
            lock (_sendLockObject)
            {
                try
                {
                    if (websocket.SendResponseToServer(qsr))
                    {
                        Growl.SuccessGlobal($"发送窗口抖动成功至服务端,内容{qsr.Message}");
                    }
                    else
                    {
                        Growl.WarningGlobal($"发送窗口抖动至服务端失败,内容{qsr.Message}");
                    }
                }
                catch (Exception ex)
                {
                    Growl.WarningGlobal($"发送窗口抖动至服务端异常,内容{qsr.Message}+{ex.Message}");
                }
            }

        }

        private void SendReviewMessageToServer(string reviewMessage)
        {
            try
            {
                QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
                qsr.UserID = UserHelper.UserID;
                qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.RequestReview;
                qsr.RequestReviewMessage = reviewMessage;
                qsr.Trade = selectedUserTrade;
                qsr.Guid = CurrentGuid;

                if(!websocket.SendResponseToServer(qsr))
                {
                    AppLog.WriteError("无法发送审核消息，服务端异常");
                    Growl.ErrorGlobal("无法发送审核消息，服务端异常");
                    return;
                }else
                {
                    Growl.SuccessGlobal("发送审核消息成功！");
                }
            }
            catch(Exception ex)
            {
                AppLog.WriteError("SendReviewMessageToServer发送审核消息时出错"+ex.Message);
            }
   
        }

        private void WebSocketHelper_QuanYiOrderClientMessageEvent(QuanYiOrderServerResponseClass QSR)
        {
            try
            {
                if (QSR.Guid == CurrentGuid)
                {
                    GlobalQSR = QSR;
                    bResponseReceived = true;
                }
                UserTrade ut;
                switch (QSR.DataType)
                {
                    case QuanYiServerBaseClass.DataTypeEnum.Order:
                        ut = TradeList.FirstOrDefault(x => x.Guid == QSR.Trade.Guid);
                        if (ut == null & QSR.Trade.UserID != 0 & (QSR.Code == 0 | QSR.Code == 4))
                        {
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                TradeList.Insert(0, QSR.Trade);
                            });
                         
 
                        }
                        SearchHandle();//刷新一次算了。
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm:
                        ut = TradeList.FirstOrDefault(x => x.Guid == QSR.Trade.Guid);
                        if (ut != null)
                        {
                            
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                ut.Price = QSR.Trade.Price;
                            });
                        }
                        SearchHandle();//刷新一次算了。
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.Trade:
                        //ut = TradeList.FirstOrDefault(x => x.Guid == QSR.Trade.Guid);
                        //if (ut != null)
                        //{
                        //    PrismApplication.Current.Dispatcher.Invoke(() =>
                        //    {
                        //        ut.Status = QSR.Trade.Status;
                        //        ut.StatusText = QSR.Trade.StatusText;
                        //    });
                         
                        //}
                        SearchHandle();//刷新一次算了。
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.Withdrawed:
                        ut = TradeList.FirstOrDefault(x => x.Guid == QSR.Trade.Guid);
                        if (ut != null)
                        {
                            
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                ut.Status = QSR.Trade.Status;
                                ut.StatusText = QSR.Trade.StatusText;
                            });
                        }
                        SearchHandle();//刷新一次算了。
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.Withdraw:
                        ut = TradeList.FirstOrDefault(x => x.Guid == QSR.Trade.Guid);
                        if (ut != null)
                        {
                            
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                ut.Status = QSR.Trade.Status;
                                ut.StatusText = QSR.Trade.StatusText;
                            });
                        }
                        SearchHandle();//刷新一次算了。
                        break;
                    

                    case QuanYiServerBaseClass.DataTypeEnum.NewChatMessageIn:

                        //HandyControl.Controls.MessageBox.Show("收到客户端用户发来的一条请求");
                        var chatList = QSR.NewChatMessageList;
                        List<ChatMessage> newMessages = new List<ChatMessage>();
                        if (chatList != null && chatList.Count > 0)
                        {
                            foreach (var item in chatList)
                            {
                                // 创建一个唯一标识符（例如组合时间戳和消息内容）
                                string uniqueIdentifier = $"{item.CreateTime}_{item.ChatMessageInfo}";

                                // 检查是否已经处理过该消息
                                if (!processedMessages.Contains(uniqueIdentifier))
                                {
                                    string brokerName = ChatReceivers.Where(o => o.Brokerid == item.BrokerId).FirstOrDefault()?.Company;
                                    string chatinfo = $"消息内容：{item.ChatMessageInfo}\r\n" +
                                                      $"时间：{item.CreateTime}\r\n" +
                                                      $"中介：{brokerName}";
                                    item.BrokerName = brokerName;
                                    //Growl.InfoGlobal($"收到一条新消息：{chatinfo}");

                                    // 添加到已处理集合中
                                    processedMessages.Add(uniqueIdentifier);
                                    // 添加到新的消息列表中
                                    newMessages.Add(item);
                                }
                                //string brokerName = ChatReceivers.Where(o=>o.Brokerid==item.BrokerId).FirstOrDefault().Company;
                                //string chatinfo = $"消息内容：{item.ChatMessageInfo}\r\n" +
                                //    $"时间：{item.CreateTime}\r\n" +
                                //    $"中介：{brokerName}";
                                //item.BrokerName = brokerName;
                                //Growl.InfoGlobal($"收到一条新消息：{chatinfo}");
                            }
                        }
                        // 仅对新的消息列表进行发送
                        if (newMessages.Count > 0)
                        {
                            Messenger.Default.Send(newMessages, MessageToken.NewChatMessageIn);
                            Messenger.Default.Send(newMessages, MessageToken.SendChatMessage);
                        }
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:

                        ChatInfoModel info = new ChatInfoModel();

                        if (AllowedBrokers.Contains(QSR.BrokerID))
                        {
                            Messenger.Default.Send(info, MessageToken.SendChatMessage);
                        }
                        break;

                    case QuanYiServerBaseClass.DataTypeEnum.PingCang:
                        if (AllowedBrokers.Contains(QSR.BrokerID))
                        {
                            Messenger.Default.Send(QSR, MessageToken.PingCangMessage);
                        }
                        break;

                        ///QTrade都没开
                    case QuanYiServerBaseClass.DataTypeEnum.QTradeNotOpen:
                        string QTradeNotOpenMessage = $"通知：{UserHelper.NickName}，QTrade程序未开启，禁止下单相关操作";
                        AppLog.WriteError(QTradeNotOpenMessage);
                        Growl.ErrorGlobal(QTradeNotOpenMessage);
                        
                        break;
                    default:
                        break;
                }

        
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "QuanyiServer" + "Socket_QuanYiClientMessageEvent" + ex.StackTrace);
                QSR.Code = 7;
                QSR.Message = ex.Message;
                //websocket.SendResponseToClient(QSR);
            }
        }
        // 全局定义一个集合用于存储已处理的消息
        private static HashSet<string> processedMessages = new HashSet<string>();
        private void Websocket_SubscribeLilyTradeEvent(LilyTradeModel Trade)
        {
            try
            {
                int id = 0;
                int.TryParse(Trade.userTradeId, out id);
                if (id != 0)
                {
                    UserTrade qct = TradeList.FirstOrDefault(x => x.UserTradeID == id);
                    if (qct != null)
                    {
                        // 使用 Dispatcher.Invoke 更新 UI 控件
                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            qct.Status = Trade.status;
                            int tradedVolume = 0;
                            int.TryParse(Trade.volume, out tradedVolume);
                            if (tradedVolume == 0)
                            {
                                return;
                            }
                            if (qct.Volume == tradedVolume)
                            {
                                qct.OnHoldVolume = 0;
                            }
                            else
                            {
                                qct.OnHoldVolume = qct.Volume - tradedVolume;
                            }
                            switch (qct.Status)
                            {
                                case 0:
                                case 1:
                                    qct.OnHoldVolume = qct.Volume;
                                    qct.StatusText = "已接收";
                                    break;
                                case 3:
                                    qct.OnHoldVolume = 0;
                                    qct.StatusText = "已成交";
                                    break;
                                case 4:
                                    qct.OnHoldVolume -= tradedVolume;
                                    qct.StatusText = "部分成交";
                                    break;
                                case 5:
                                    qct.OnHoldVolume = 0;
                                    qct.StatusText = "已撤单";
                                    break;
                                case 6:
                                    qct.OnHoldVolume -= tradedVolume;
                                    qct.StatusText = "部分撤单";
                                    break;
                                case 9:
                                    qct.StatusText = "待确认";
                                    break;
                                case 13:
                                    qct.StatusText = "已作废";
                                    break;
                                default:
                                    qct.OnHoldVolume = 0;
                                    qct.StatusText = "已完成";
                                    break;
                            }
                        });

                        AppLog.WriteInfo("执行操作：" +"将指令——"+qct.Command+"的状态改为：" + qct.StatusText
                            +"类型："+qct.DealType
                            +"剩余容量"+qct.OnHoldVolume
                            +"价格："+qct.Price);
                      
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并进行适当的处理，例如记录日志
                AppLog.WriteError($"Error in Websocket_SubscribeLilyTradeEvent: {ex.Message}");
            }
        }


        private void Websocket_OrderServerDisconnectedEvent()
        {
            AppLog.WriteError($"与服务端断开连接，正在尝试重连");
            //Growl.WarningGlobal("与服务端断开连接，正在尝试重连");
            try
            {
                StartReconnectTimer();
            }
            catch (Exception ex)
            {
                AppLog.WriteError("Websocket_OrderServerDisconnectedEvent异常" + ex.Message + ex.StackTrace);
            }

        }

        private void Websocket_ServerConnectedEvent()
        {
            Growl.SuccessGlobal("与服务端成功连接");
        }


        #region 其余依赖属性
        private ObservableCollection<UserTrade> tradeList;

        /// <summary>
        /// 所有交易列表
        /// </summary>
        public ObservableCollection<UserTrade> TradeList
        {
            get { return tradeList; }
            set { tradeList = value; RaisePropertyChanged(); }

        }

        private void TradeList_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // 不在事件处理程序中修改集合
            var tempTradeList = TradeList.ToList();
            int totalCount = TradeList.Count;

            // 使用 Dispatcher 确保在 UI 线程中更新 StaticTradeList
            PrismApplication.Current.Dispatcher.Invoke(() =>
            {
                StaticTradeList = tempTradeList;
                TotalDataCount = totalCount;
            });

        }


        //private ObservableCollection<UserTrade> filteredTradeList;

        ///// <summary>
        ///// 过滤后的交易列表
        ///// </summary>
        //public ObservableCollection<UserTrade> FilteredTradeList
        //{
        //    get { return filteredTradeList; }
        //    set { filteredTradeList = value; RaisePropertyChanged(); }
        //}

        private DateTime _selectedStartDate = DateTime.Now.Date;
        public DateTime SelectedStartDate
        {
            get { return _selectedStartDate; }
            set
            {
                if (_selectedStartDate != value)
                {
                    _selectedStartDate = value;
                    RaisePropertyChanged();
                }
            }
        }
        private DateTime _selectedEndDate = DateTime.Now.Date;
        /// <summary>
        /// 筛选的交易日区间
        /// </summary>
        public DateTime SelectedEndDate
        {
            get { return _selectedEndDate; }
            set
            {
                if (_selectedEndDate != value)
                {
                    _selectedEndDate = value;
                    RaisePropertyChanged();
                }
            }
        }
        private string searchText;

        /// <summary>
        /// 查询过滤的文本框
        /// </summary>
        public string SearchText
        {
            get { return searchText; }
            set { searchText = value;RaisePropertyChanged(); }
        }

        private string orderStatus="正常";

        public string OrderStatus
        {
            get { return orderStatus; }
            set { orderStatus = value;RaisePropertyChanged(); }
        }


        private bool isSelected = false; //判断是不是处于搜索状态下
        #endregion


        #region 强平显示相关

        /// <summary>
        /// 强制强平，禁止一切操作
        /// </summary>
        /// 
        public static bool IsQiangPing = false;
        public static void ShowQiangPing(string qiangPingMessage="null",int timeSeconds=0)
        {
            string tradeStr = null;
            string message =
           "系统警告：强平警告！" + "\r\n" +
            qiangPingMessage;
            // 使用 HandyControl 的 DialogService 显示 QiangPingWindow
            // 使用 HandyControl 的 Dialog.Show 方法显示 QiangPingWindow
            // 使用 HandyControl 的 Dialog.Show 方法显示 QiangPingWindow

            // 创建一个 QiangPingWindow 的实例
            if(timeSeconds!=0)
            {

                ShowQiangPingCountDownFiveMinutes(timeSeconds);
            }
            else
            {
                var qiangPingWindow = new QiangPingWindow(message);
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    Dialog.Show(qiangPingWindow);
                });
            }
           
            //if (StaticTradeList!=null&&StaticTradeList.Count>0)
            //{
            //    var tradeFirst = StaticTradeList.First();

            //    if (tradeFirst != null)
            //    {
            //        tradeStr = "强平信息:" + "\r\n" +
            //            $"中介——{tradeFirst.Broker}, 交易类型——{tradeFirst.OrderType}" + "\r\n" +
            //            $"券码——{tradeFirst.TsCode}, 价格——{tradeFirst.Price}" + "\r\n" +
            //            $"状态——{tradeFirst.StatusText}, 量——{tradeFirst.Volume}" + "\r\n";
            //    }
            //}


            //string message = 
            //"系统警告：强平警告！"+"\r\n"+
            //"重要通知：强平事件发生！"+"\r\n"+
            //"紧急提示：请注意强平消息！"+"\r\n\n"+tradeStr+qiangPingMessage;


        }

        public static QiangPingCountDownView _qiangPingCountDownWindow;

        /// <summary>
        /// 五分钟后强平
        /// </summary>
        public static void ShowQiangPingCountDownFiveMinutes(int seconds)
        {
            if (_qiangPingCountDownWindow != null)
            {
                return;
            }
            // 计算小时、分钟和秒钟
            int hour = seconds / 3600;
            int minute = (seconds % 3600) / 60;
            int second = seconds % 60;
            // 创建新的窗口实例
            _qiangPingCountDownWindow = new QiangPingCountDownView(hour, minute, second);

            // 获取屏幕分辨率
            double screenWidth = SystemParameters.PrimaryScreenWidth;
            double screenHeight = SystemParameters.PrimaryScreenHeight;

            // 计算窗口的起始位置
            double windowWidth = _qiangPingCountDownWindow.Width;
            double windowHeight = _qiangPingCountDownWindow.Height;

            double left = (screenWidth - windowWidth) / 2;
            double top = 20; // 最上面的位置

            // 设置窗口位置
            _qiangPingCountDownWindow.Left = left;
            _qiangPingCountDownWindow.Top = top;

            PrismApplication.Current.Dispatcher.Invoke(() =>
            {
                _qiangPingCountDownWindow.Show();
            });
          
        }

        public static List<string> WhiteTscodeList=new List<string>();
        public static bool CheckIfInWhiteList(string tsCode)
        {
            //WhiteTscodeList = UserHelper.GetTscodeWhiteList();
            if(WhiteTscodeList != null)
            {
                if(WhiteTscodeList.Contains(tsCode))
                {
                    return true;
                }
            }
            return false;

   
        }
        #endregion

    }

    #region 和lily对接的类
    public class CreateTimeFromLily
    {
        public int Year { get; set; }
        public int MonthValue { get; set; }
        public int DayOfMonth { get; set; }
        public int Hour { get; set; }
        public int Minute { get; set; }
        public int Second { get; set; }
        public int Nano { get; set; }
    }

    public class ChatDataFromLily
    {
        public string Id { get; set; }
        public int ChatId { get; set; }
        public string ChatMessage { get; set; }
        public int BrokerId { get; set; }
        public int Direction { get; set; }
        public CreateTimeFromLily CreateTime { get; set; }
        public string? TradeId { get; set; }
        public object IsTrade { get; set; }
        public CreateTimeFromLily UpdateTime { get; set; }
        public object QuoteMessage { get; set; }
        public string ChannelId { get; set; }
        public string BrokerName { get; set; } // 添加 BrokerName 字段
    }

    public class RootFromLily
    {
        public string? DataKey { get; set; }
        public string? DataType { get; set; }
        public string? ActionType { get; set; }
        public ChatDataFromLily? Data { get; set; }
    }

    public class TradeDataFromLily
    {
        public string DataKey { get; set; }
        public string DataType { get; set; }
        public string ActionType { get; set; }
        public TradeDetailsFromLily Data { get; set; }
    }

    public class TradeDetailsFromLily
    {
        public string Tscode { get; set; }
        public string Volume { get; set; }
        public double Price { get; set; }
        public string CreateTime { get; set; }
        public string DeliveryTime { get; set; }
        public int Status { get; set; }
    }
    #endregion
}
